<script setup lang="ts">
import type { FormRules } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'

interface Props {
  data?: Record<string, any> | never | null
  status?: string | never | null
}

const props = withDefaults(defineProps<Props>(), {
  data: null,
  status: 'add'
})

const formRef = ref()

const form = ref<Record<string, any>>({})

const rules = reactive<FormRules>({
  roleName: [{ required: true, message: '名称不能为空!', trigger: 'blur' }],
  remark: [{ required: true, message: '描述不能为空!', trigger: 'blur' }]
})

const initForm = () => {
  if (props.data) {
    Object.keys(props.data).forEach((key: string) => {
      form.value[key] = props.data![key]
    })
  }
}

const formatForm = () => {
  const { roleId, roleName, remark } = form.value
  const result: Record<string, any> = {
    roleName,
    remark
  }
  if (props.status === 'edit') {
    // 更新
    result.roleId = roleId
  }
  return result
}

const submitForm = () => {
  return new Promise<any>((resolve) => {
    formRef.value.validate((valid: boolean) => {
      let res = null
      if (valid) {
        res = formatForm()
      }
      resolve(res)
    })
  })
}

defineExpose({
  submitForm
})

onMounted(() => {
  initForm()
})
</script>

<template>
  <div class="form-wrapper">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="60px">
      <el-form-item label="名称:" prop="roleName">
        <el-input v-model="form.roleName" type="text" placeholder="请输入内容" maxlength="20" show-word-limit> </el-input>
      </el-form-item>
      <el-form-item label="描述:" prop="remark">
        <el-input v-model="form.remark" type="text" placeholder="请输入内容" maxlength="20" show-word-limit> </el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="scss" scoped></style>
